import re

from django.http import JsonResponse
from django.shortcuts import render,redirect
from django.http import HttpResponse,HttpResponseForbidden

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.users.models import User

# 1用户注册信息的检查
from utils.response_code import RETCODE


class RegisterView(View):
    """用户注册"""
    def get(self,request):
        return render(request,'register.html')


    # 获取一个post请求
    def post(self,request):
        # 1.从浏览器获取用户输入的数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        sms_code = request.POST.get('sms_code')
        allow = request.POST.get('allow')
        # 2.验证数据是否正确
        if not all([username, password, password2, mobile, allow]):
            return  HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return HttpResponseForbidden('请输入5-20个字符的用户名')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('请输入8-20位的密码')
        if password2 != password:
            return HttpResponseForbidden('两次的密码不一致')
        if not re.match('^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden('输入的')
        if allow != 'on':
            return HttpResponseForbidden('请勾选用户协议')

            # 3.写入数据库
        try:
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except Exception as ret:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})
        else:
            from django.contrib.auth import login
            login(request,user)
            # 5.重定向网页
            return redirect(reverse('contents:index'))

# 判断用户名是否重复
class UsernameCountView(View):
    """判断用户名是否重复"""
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})

class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        """
        :param request: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})





